var express = require("express");
var router = express.Router();
const charProductModel = require("../../models/characteristicProductModel");

// 获取特色农产品列表
router.get("/info", (req, res) => {
  let { pageNo, pageSize } = req.query;
  if (pageNo === "undefined" || pageSize === "undefined") {
    charProductModel
      .find()
      .select({ __v: 0 })
      .then((data) => {
        if (data.length === 0) {
          return res.json({
            code: 200,
            msg: "数据为空",
            data: data,
          });
        }
        return res.json({
          code: 200,
          msg: "获取农产品列表成功",
          data: data,
        });
      })
      .catch((err) => {
        return res.json({
          code: "1001",
          msg: "数据库读取失败~~~",
          data: null,
        });
      });
  } else {
    charProductModel
      .find()
      .then((result) => {
        if (result.length === 0) {
          return res.json({
            code: 200,
            msg: "数据为空",
            data: null,
          });
        } else {
          charProductModel
            .find()
            .select({ __v: 0 })
            .skip((pageNo - 1) * pageSize)
            .limit(pageSize)
            .then((data) => {
              let total = result.length;
              return res.json({
                code: 200,
                msg: "获取农产品成功",
                data: data,
                total: total,
              });
            })
            .catch((err) => {
              return res.json({
                code: "1001",
                msg: "数据库读取失败~",
                data: null,
              });
            });
        }
      })
      .catch((err) => {
        return res.json({
          code: "1001",
          msg: "数据库读取失败~",
          data: null,
        });
      });
  }
});

// 获取首页特色农产品数据
router.get("/", (req, res) => {
  charProductModel
    .find()
    .limit(15)
    .select({ __v: 0 })
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          msg: "数据为空",
          data: data,
        });
      }
      return res.json({
        code: 200,
        msg: "获取农产品列表成功",
        data: data,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

module.exports = router;
